package lvbu.wang.lvbuoperator.core;

import android.app.Application;
import android.support.v7.app.AppCompatDelegate;

import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.qing.library.utils.L;
import com.tencent.bugly.crashreport.CrashReport;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import cn.jpush.android.api.JPushInterface;
import lvbu.wang.lvbuoperator.bean.BleMotorInfo;
import lvbu.wang.lvbuoperator.bean.MotorInfo;
import lvbu.wang.lvbuoperator.manager.ThreadPool;
import lvbu.wang.lvbuoperator.services.BluetoothLEService;

/**
 * Created by DaiQing.Zha on 2016/6/8 0008.
 * Email:1642674371@qq.com
 * Description:
 */
public class App extends Application {

    private static App mInstance;
    private MotorInfo motorInfo;
    private static final String SAVE_MotorInfo_FILENAME = "motor";
    private BleMotorInfo bleMotorInfo;
    private static final String SAVE_Bike_MotorInfo_FILENAME = "save_bike_motorinfo_filename";
    @Override
    public void onCreate() {
        super.onCreate();
        mInstance = this;

        /**
         * 配置ImageLoader
         */
        ImageLoaderConfiguration configuration = ImageLoaderConfiguration.createDefault(this);
        ImageLoader.getInstance().init(configuration);
        /**
         * 腾讯bugly
         */
        CrashReport.initCrashReport(this, "608f39312c", false);

        JPushInterface.setDebugMode(true); 	// 设置开启日志,发布时请关闭日志
        JPushInterface.init(this);     		// 初始化 JPush
        AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);
    }

    @Override
    public void onTerminate() {
        L.e("BNBNNNNNN");
        super.onTerminate();
    }

    public static App getInstance() {
        return mInstance;
    }

    private RequestQueue requestQueue;
    public RequestQueue getRequestQueue() {
        if (requestQueue == null) {
            synchronized (this) {
                if (requestQueue == null) {
                    requestQueue = Volley.newRequestQueue(this);
                }
            }
        }
        return requestQueue;
    }
    /**
     * 登录成功后保存电机信息
     */
    public MotorInfo getMotorInfo() {
        if (motorInfo == null) {		//如果不为null，说明user信息还在内存中保存
            File file = new File(getFilesDir().getAbsolutePath(),
                    SAVE_MotorInfo_FILENAME);
            FileInputStream fis = null;
            ObjectInputStream ois = null;
            try {
                if (!file.exists()) {
                    // 如果该文件不存在，
                    file.createNewFile();
                    return new MotorInfo();
                }
                fis = new FileInputStream(file);
                ois = new ObjectInputStream(fis);
                motorInfo = (MotorInfo) ois.readObject();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (ois != null) {
                    try {
                        ois.close();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
            if (motorInfo == null) {// 如果这里还是为null,说明，应该创建一个user.但是没有任何的数据
                motorInfo = new MotorInfo();
            }
        }
        return motorInfo;
    }

    public void setMotor(MotorInfo motorInfo) {
        this.motorInfo = motorInfo;
        saveMotorInfoToFile(motorInfo);
    }

    public void setMotorAndsetBlueToothStatus(MotorInfo motorInfo) {
        this.motorInfo = motorInfo;
        saveMotorInfoToFile(motorInfo);
        BaseActivity.saveMotorDefault_bluetooth_connect_state(getApplicationContext(), BluetoothLEService.Bluetooth_UNCONNECT);
    }

    /**
     * 保存电机
     * @param motorInfo
     */
    private void saveMotorInfoToFile(final MotorInfo motorInfo) {

        ThreadPool.getInstance().addTask(new Runnable() {
            @Override
            public void run() {
                File file = new File(getFilesDir().getAbsolutePath(),
                        SAVE_MotorInfo_FILENAME);
                FileOutputStream fos = null;
                ObjectOutputStream oos = null;
                try {
                    if (!file.exists()) {
                        file.createNewFile();
                    }
                    fos = new FileOutputStream(file);
                    oos = new ObjectOutputStream(fos);
                    oos.writeObject(motorInfo);
                    oos.flush();
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (fos != null) {
                        try {
                            fos.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (oos != null) {
                        try {
                            oos.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        });
    }


    /**
     * 登录成功后保存电机信息
     */
    public BleMotorInfo getBleMotorInfo() {
        if (bleMotorInfo == null) {		//如果不为null，说明user信息还在内存中保存
            File file = new File(getFilesDir().getAbsolutePath(),
                    SAVE_Bike_MotorInfo_FILENAME);
            FileInputStream fis = null;
            ObjectInputStream ois = null;
            try {
                if (!file.exists()) {
                    // 如果该文件不存在，
                    file.createNewFile();
                    return new BleMotorInfo();
                }
                fis = new FileInputStream(file);
                ois = new ObjectInputStream(fis);
                bleMotorInfo = (BleMotorInfo) ois.readObject();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (ois != null) {
                    try {
                        ois.close();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
            if (bleMotorInfo == null) {// 如果这里还是为null,说明，应该创建一个user.但是没有任何的数据
                bleMotorInfo = new BleMotorInfo();
            }
        }
        return bleMotorInfo;
    }

    public void setBikeMotor(BleMotorInfo motorInfo) {
        this.bleMotorInfo = motorInfo;
        saveBikeMotorInfoToFile(motorInfo);
    }

    public void setBikeMotorAndsetBlueToothStatus(BleMotorInfo motorInfo) {
        this.bleMotorInfo = motorInfo;
        saveBikeMotorInfoToFile(motorInfo);
        BaseActivity.saveMotorDefault_bluetooth_connect_state(getApplicationContext(), BluetoothLEService.Bluetooth_UNCONNECT);
    }

    /**
     * 保存电机
     * @param motorInfo
     */
    private void saveBikeMotorInfoToFile(final BleMotorInfo motorInfo) {

        ThreadPool.getInstance().addTask(new Runnable() {
            @Override
            public void run() {
                File file = new File(getFilesDir().getAbsolutePath(),
                        SAVE_Bike_MotorInfo_FILENAME);
                FileOutputStream fos = null;
                ObjectOutputStream oos = null;
                try {
                    if (!file.exists()) {
                        file.createNewFile();
                    }
                    fos = new FileOutputStream(file);
                    oos = new ObjectOutputStream(fos);
                    oos.writeObject(motorInfo);
                    oos.flush();
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (fos != null) {
                        try {
                            fos.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (oos != null) {
                        try {
                            oos.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        });
    }
}
